package com.example.qing.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.example.qing.config.MyLogs;
import com.example.qing.pojo.Logs;
import com.example.qing.pojo.User;
import com.example.qing.service.LogService;
import com.example.qing.utils.JwtUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Resource
    LogService logService;

    @AfterReturning(pointcut = "@annotation(myLogs)")
    public void recordLog(JoinPoint joinPoint, MyLogs myLogs){
        User loginUser= JwtUtils.getCurrentUser();
        log.info("qwq");
        if(loginUser==null){
            Object[]args=joinPoint.getArgs();
            if(ArrayUtil.isNotEmpty(args)){
                if (args[0] instanceof User){
                    loginUser=(User) args[0];
                }
            }
            if (loginUser==null){
                log.error("未获取到用户信息");
                return ;
            }
        }
        Logs logs=Logs.builder()
                .user(loginUser.getUsername())
                .type(myLogs.type().getValue())
                .module(myLogs.operation())
                .time(DateUtil.now())
                .build();

        ThreadUtil.execAsync(()->{
            logService.save(logs);
        });

    }
}
